package com.kitty.game.identity;


import com.kitty.common.db.Db4CommonService;
import com.kitty.game.ServerService;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class IdentityService {
    @Autowired
    private Dao dao;

    private Map<Integer, IdentityEnt> map = new HashMap<>();

    private AtomicInteger defaultFactory = new AtomicInteger(1);

    public void init() {
        for (IdentityType kind : IdentityType.values()) {
            int type1 = kind.getType();
            if (!kind.isSave()) {
                continue;
            }
            IdentityEnt ent = dao.fetch(IdentityEnt.class, Cnd.where("type", "=", type1));
            if (ent == null) {
                ent = IdentityEnt.valueOf(type1, createInitSeed());
                dao.insertOrUpdate(ent);
            }
            map.put(ent.getType(), ent);
        }
    }

    private int createInitSeed() {
        // serverId只有5位，最大为31。。。
        return ServerService.serverId << 25;
    }

    public int getNextId(IdentityType idType) {
        if (!idType.isSave()) {
            return defaultFactory.getAndIncrement();
        }
        int type = idType.getType();
        IdentityEnt ent = map.get(type);
        int nextId = ent.getNextId();
        Db4CommonService.getInstance().add2Queue(ent);

        return nextId;
    }
}
